package net.mikoo.seals.boss.biz.services.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;

import net.mikoo.seals.boss.biz.manager.CompanyManager;
import net.mikoo.seals.boss.biz.mapper.client.CompanyMapper;
import net.mikoo.seals.boss.biz.mapper.client.MemberMapper;
import net.mikoo.seals.boss.biz.mapper.client.StaffMapper;
import net.mikoo.seals.boss.biz.services.MemberServices;
import net.mikoo.seals.boss.common.BaseServices;
import net.mikoo.seals.boss.common.PageModel;
import net.mikoo.seals.boss.common.WebContext;
import net.mikoo.seals.boss.common.enums.CompanyStatusEnum;
import net.mikoo.seals.boss.common.enums.MobileStatusEnum;
import net.mikoo.seals.boss.common.enums.StaffStatusEnum;
import net.mikoo.seals.boss.common.exception.ParametersException;
import net.mikoo.seals.boss.common.utils.IPUtil;
import net.mikoo.seals.boss.common.utils.MD5Util;
import net.mikoo.seals.boss.model.Company;
import net.mikoo.seals.boss.model.MemberQuery;
import net.mikoo.seals.boss.model.Party;
import net.mikoo.seals.boss.model.Person;
import net.mikoo.seals.boss.model.Staff;
import net.mikoo.seals.boss.model.StaffQuery;
import net.mikoo.seals.boss.model.UserLogin;

public class MemberServicesImpl extends BaseServices implements MemberServices {

	private Logger logger = LoggerFactory.getLogger(MemberServicesImpl.class);

	@Autowired
	private MemberMapper memberMapper;
	
	@Autowired
	private CompanyMapper companyMapper;
	
	@Autowired
	private CompanyManager companyManager;
	
	@Autowired
	private StaffMapper staffMapper;

	@Override
	public PageModel<Party> getToPageByQuery(MemberQuery query) {
		List<Party> datas = memberMapper.selectToPageByQuery(query);
		Integer total = memberMapper.countToPageByQuery(query);
		PageModel<Party> pm = new PageModel<>(total, datas);
		return pm;
	}

	@Override
	public void create(Party party) {
		
		companyManager.checkCreateAccountParms(party);
		
		StaffQuery query = new StaffQuery();
		query.setCompanyId(party.getCompanyId());
		query.setMobile(party.getUserLoginId());
		Staff exist = staffMapper.selectInfoByQuery(query);
		if(exist !=null) {
			throw new ParametersException("此账户已存在");
		}
		
		//判断注册管理员用户是否已经存在 如果不存在重新创建、已存在关联公司
		UserLogin userLogin = memberMapper.selectByUserLoginId(party.getUserLoginId());
		if(userLogin != null) {
			Staff staff = new Staff();
			staff.setStaffType("ADMIN");
			staff.setPartyId(userLogin.getPartyId());
			staff.setCompanyId(party.getCompanyId());
			staff.setName(party.getPerson().getName());
			staff.setMobile(userLogin.getPerson().getMobile());
			staff.setIsSystem("Y");
			staff.setCreateTime(new Date());
			staff.setStaffStatus(StaffStatusEnum.NORMAL.code());
			staffMapper.insert(staff);
			
			
			Company company = new Company();
			company.setCompanyId(party.getCompanyId());
			company.setUserLoginId(userLogin.getUserLoginId());
			company.setPartyId(userLogin.getPartyId());
			company.setCompanyStatus(CompanyStatusEnum.ACTIVITY.code());
			companyMapper.updateManagerAccount(company);
		}else {
			
			clientTransactionTemplate.execute(new TransactionCallbackWithoutResult() {

				@Override
				protected void doInTransactionWithoutResult(TransactionStatus status) {
					try {


						// 验证用户名
						UserLogin userLogin = party.getUserLogin();
						Person person = party.getPerson();
						
						
						String userLoginId = userLogin.getUserLoginId();
						if (StringUtils.isBlank(userLoginId)) {
							throw new ParametersException("userLoginId is blank");
						}
						
						person.setMobile(userLoginId);

						boolean b = isExist(userLoginId, null, "username");
						if (b) {
							throw new ParametersException("登陆账户已存在");

						}
						// 验证密码字段
						String password = userLogin.getCurrentPassword();
						if (StringUtils.isBlank(password)) {
							throw new ParametersException("password is blank");
						}

						String email = person.getEmail();
						if (StringUtils.isNotBlank(email) && isExist(email, null, "email")) {
							throw new ParametersException("邮箱账户已存在");
						}

						String mobile = person.getMobile();
						if (StringUtils.isNotBlank(mobile) && isExist(mobile, null, "mobile")) {
							throw new ParametersException("手机号码已存在");
						}

						// 创建party
						
						party.setUserLoginId(userLogin.getUserLoginId());
						party.setCreatedTime(new Date());
						party.setIsSystem("Y");
						memberMapper.insertBackPrimaryKey(party);

						// 创建登录帐户

						userLogin.setCurrentPassword(MD5Util.Md5(userLogin.getCurrentPassword()));
						userLogin.setPartyId(party.getPartyId());
						userLogin.setRegisterTime(new Date());
						userLogin.setRegisterIp(IPUtil.getRemoteAddr(WebContext.getRequest()));
						userLogin.setIsSystem("Y");
						memberMapper.insertUserLogin(userLogin);

						// 创建人员信息
						person.setUserLoginId(userLogin.getUserLoginId());
						person.setPartyId(party.getPartyId());
						person.setMobileStatus(MobileStatusEnum.NOT_CERTIFIED.code());
						memberMapper.insertPerson(person);
						
						//创建管理员和公司关联信息
						Staff staff = new Staff();
						staff.setStaffType("ADMIN");
						staff.setPartyId(userLogin.getPartyId());
						staff.setCompanyId(party.getCompanyId());
						staff.setName(party.getPerson().getName());
						staff.setMobile(party.getPerson().getMobile());
						staff.setIsSystem("Y");
						staff.setCreateTime(new Date());
						staff.setStaffStatus(StaffStatusEnum.NORMAL.code());
						staffMapper.insert(staff);
						
						
						Company company = new Company();
						company.setCompanyId(party.getCompanyId());
						company.setUserLoginId(userLogin.getUserLoginId());
						company.setPartyId(party.getPartyId());
						company.setCompanyStatus(CompanyStatusEnum.ACTIVITY.code());
						companyMapper.updateManagerAccount(company);

					} catch (ParametersException e) {
						logger.error("", e);
						status.setRollbackOnly();
						throw e;
					} catch (Exception e) {
						logger.error("", e);
						status.setRollbackOnly();
						throw e;
					}

				}

			});
		}
	}
	
	
	/**
	 * 判断字段是否唯一
	 * @param verifykey
	 * @param excludeKey
	 * @param type
	 * @return
	 */
	private boolean isExist(String verifykey, String excludeKey, String type) {
		boolean b = false;
		switch (type) {
			case "username":
				
				UserLogin userLogin = memberMapper.selectByUserLoginId(verifykey);
				if (userLogin == null) {
					b = false;
				} else {
					
					b = true;
					if (StringUtils.isNotBlank(excludeKey)) {
						if (verifykey.equals(userLogin.getUserLoginId())) {
							b = false;
						}
					}
				}
				break;
			
			case "mobile":
				Person mPerson = memberMapper.selectByMobile(verifykey);
				if (mPerson == null) {
					b = false;
				} else {
					
					b = true;
					
					if (StringUtils.isNotBlank(excludeKey)) {
						if (verifykey.equals(mPerson.getMobile())) {
							b = false;
						}
					}
				}
				break;
			
			case "email":
				
				Person ePerson = memberMapper.selectByEmail(verifykey);
				if (ePerson == null) {
					b = false;
				} else {
					b = true;
					if (StringUtils.isNotBlank(excludeKey)) {
						if (verifykey.equals(ePerson.getEmail())) {
							b = false;
						}
					}
				}
				
				break;
			default:
				
				break;
		}
		
		return b;
	}

	@Override
	public Party getByPartyId(Long partyId) {
		
		Party party = memberMapper.selectByPartyId(partyId);
		
		return party;
	}

	@Override
	public Staff getLegalPersonByCompanyId(Long companyId) {
	
		
		Staff party = 	memberMapper.selectLegalPersonByCompanyId(companyId);
		
		
		return party;
	}

}
